package com.example.luckysystem.common.pojo;

import com.example.luckysystem.common.errorcode.ErrorCode;
import com.example.luckysystem.common.errorcode.GlobalErrorCodeConstants;
import lombok.Data;
import org.springframework.util.Assert;

import java.io.Serializable;

/**
 * @version 1.0
 * @Author shangjialu
 * @Date 2024/12/4 22:23
 * @注释
 */
@Data
public class CommonResult<T> implements Serializable {
//    CommonResult<T>是在http中进行传输，所以要进行序列化
    private Integer code;//返回的错误码
    private T data;//返回的数据
    private String msg;//对错误码的描述

    //返回成功结果的CommonResult<T>静态构造
    public static <T> CommonResult<T> success(T data){
        CommonResult<T> result = new CommonResult<>();
        result.code = GlobalErrorCodeConstants.SUCCESS.getCode();
        result.data = data;
        result.msg = "";
        return result;
    }

    //返回异常结果的CommonResult<T>静态构造
    public static <T> CommonResult<T> error(Integer code,String msg){
        Assert.isTrue(!GlobalErrorCodeConstants.SUCCESS.getCode().equals(code),"code不是错误的异常");
        CommonResult<T> result = new CommonResult<>();
        result.code = code;
        result.msg = msg;
        return result;
    }

    public static <T> CommonResult<T> error(ErrorCode errorCode){
        return error(errorCode.getCode(),errorCode.getMsg());
    }
}
